package com.yidu.view;

import com.yidu.dao.BookUserMapper;
import com.yidu.domain.BookUser;
import com.yidu.utils.BaseMessage;
import com.yidu.utils.SqlSessionTools;
import com.yidu.utils.Tools;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <p>@Description: No Description</p>
 * <p>@Author yidu-liandyao</p>
 * <p>@Date: 2021-01-06</p>
 * <p>@Time: 8:54</p>
 */
@WebServlet("/BookUserServlet")
public class BookUserServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //设置请求和响应的编码
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if("login".equals(action)){
            login(request,response);
        }
    }

    /**
     * 登录
     * @param request
     * @param response
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");
        SqlSession sqlSession = SqlSessionTools.getSession();
        BookUserMapper mapper = sqlSession.getMapper(BookUserMapper.class);
        BookUser userVo = new BookUser();
        userVo.setUserPwd(userPwd);
        userVo.setUserName(userName);
        //从数据库查询到数据
        /*

        Expected one result
        (or null) to be returned by selectOne(),
         but found: 3

         返回多个值,但是你的预期只有一个值
       */
        List<BookUser> list = mapper.findLogin(userVo);

        //自定义的一个消息类,里面包含状态,消息,和数据
        BaseMessage message = new BaseMessage();
        if(list.size()>0){
            message.setState(1);
            message.setMsg("登录成功");
            message.setData(list.get(0));
            request.getSession().setAttribute("user",list.get(0));
        }else{
            message.setState(0);
            message.setMsg("登录失败");
        }

        Tools.write(response,message);

    }
}
